<!-- 頁面導航 -->
<template>
  <div class="navigator-wrapper">
    <wxc-tab-page ref="wxc-tab-page"
                  :tab-titles="tabTitles"
                  :tab-styles="tabStyles"
                  title-type="icon"
                  :tab-page-height="tabPageHeight"
                  :wrap-bg-color="wrapBgColor">
      <list v-for="(v,index) in tabList"
            :key="index"
            class="item-container"
            :style="{ height: (tabPageHeight - tabStyles.height - tabMarginHeight) + 'px' }">
        <cell v-for="(item,key) in v.items"
              class="cell"
              :key="key">
          <wxc-pan-item :ext-id="'1-' + (v) + '-' + (key)"
                        @wxcPanItemPan="wxcPanItemPan">
            <div class="content">
              <div class="item-image" :style="{ 'background-image': 'url(' + item.avatar + ')'}"></div>
              <div class="item-info">
                <div class="title">
                  <text>{{item.title}}</text>
                </div>
                <div class="sales">
                  <text>{{language.volume}} {{item.sales}}</text>
                </div>
                <div class="price">
                  <text :class="item.price.symbol">{{item.price.amount}}</text>
                </div>
                <div class="fixed">
                  <div v-if="item.attributes.length > 0">
                    <wxc-button :text="language.chooseAttribute" size="small" :btn-style="chooseAttributesButtonStyle" @wxcButtonClicked="chooseAttributes(item, index, key)"></wxc-button>
                    <wxc-tag class="shopping-cart-num-tag"
                      v-if="item.num > 0"
                      type="solid"
                      tag-color="#ffdb2b"
                      font-color="#f66c4f"
                      :value="item.num"></wxc-tag>
                  </div>
                  <div v-else-if="item.inShoppingCart">
                    <div class="count-stepper">
                      <wxc-stepper
                        :default-value="item.num"
                        max="99"
                        min="0"
                        :read-only="true"
                        @wxcStepperValueIsMinOver="editShoppingCart('0', index, key)"
                        @wxcStepperValueChanged="event => wxcStepperValueChanged(event, index, key)"></wxc-stepper>
                    </div>
                  </div>
                  <i v-else class="iconfont icon-add" @click="editShoppingCart('1', index, key)"></i>
                </div>
              </div>
            </div>
          </wxc-pan-item>
        </cell>
      </list>
    </wxc-tab-page>
    <!-- Attributes Overlay -->
    <attributes
      :food="this.food"
      :categoryIndex="this.categoryIndex"
      :foodIndex="this.foodIndex"
      :attributesVisiabled="this.attributesVisiabled"
      @changeFoodNumberInShoppingCart="handleFoodNumberInShoppingCart"
      @changeAttributesVisiabled="handleAttributesVisiabled"></attributes>
  </div>
</template>

<style lang="scss">
/* 導航樣式 */
.navigator-wrapper {
  .wxc-tab-page {
    overflow: hidden;

    .tab-title-list {
      margin: 20px 25px;

      .title-item {
        border-radius: 20px;
        border: 3px solid #F45551;
        margin-right: 20px;

        &:last-child {
          margin-right: 0;
        }

        figure {
          margin-bottom: 10px;
        }
      }
    }

    .item-container {
      width: 750px;

      .border-cell {
        background-color: #FBFBFB;
        width: 750px;
        height: 24px;
        align-items: center;
        justify-content: center;
      }

      .content {
        width:750px;
        height:250px;
        align-items: center;
        justify-content: center;
        display: flex;
        flex-direction: row;
        padding: 0 25px;
        justify-content: flex-start;
        margin-bottom: 25px;

        .item-image {
          width: 250px;
          height: 250px;
          background-size: cover;
          border-top-left-radius: 20px;
          border-bottom-left-radius: 20px;
          background-position: center;
        }

        .item-info {
          width: 450px;
          height: 250px;
          padding: 25px 25px 25px 40px;
          flex-direction: column;
          min-width: 0;
          background-color: #FFFFFF;
          box-shadow: 1px 1px 0.06667rem rgba(204,204,204, 0.5);
          border-top-right-radius: 20px;
          border-bottom-right-radius: 20px;
          position: relative;

          .title {
            p {
              height: 60px;
              line-height: 60px;
              overflow: hidden;
              font-size: 30px;
            }
          }

          .sales {
            p {
              height: 60px;
              line-height: 60px;
              overflow: hidden;
              color: #757575;
              font-size: 30px;
            }
          }

          .price {
            p {
              height: 110px;
              line-height: 110px;
              overflow: hidden;
              color: #f45551;
              font-size: 46px;

              &.yen:before {
                content: "¥";
                font-size: 30px;
                padding-right: 10px;
              }

              &.mop:before {
                content: "mop";
                font-size: 30px;
                padding-right: 5px;
              }
            }
          }

          .icon-add {
            color: #f45551;
            font-size: 46px;
          }

          .count-stepper {
            .stepper-plus, .stepper-minus {
              width: 50px;
              margin-top:0px;
            }

            .stepper-input {
              width: 50px;
              border-radius: 0;

              &:disabled {
                color: #ffffff;
                -webkit-text-fill-color:#ffffff;
                -webkit-opacity:1;
                opacity: 1;
              }
            }
          }

          .shopping-cart-num-tag {
            width: fit-content;
            position: absolute;
            right: 0;
            top: -22px;

            .tag-item {
              border-radius: 50%;
              width: 40px;
              height: 40px;

              .tag-text {
                padding: 0;
                height: auto
              }
            }
          }

          .fixed {
            position: absolute;
            bottom: 28px;
            right: 28px;
          }
        }
      }
    }
  }
}
</style>

<script>
import Vue from 'vue'
import { i18n } from '@/renderer/modules/lang'
import { WxcTabPage, WxcPanItem, WxcStepper, WxcTag, Utils, BindEnv, WxcButton } from 'weex-ui'
import Attributes from '@/components/layouts/attributes'
export default {
  components: { WxcTabPage, WxcPanItem, WxcTag, WxcButton, WxcStepper, Attributes },
  props: {
    categories: {
      type: Array,
      required: true
    }
  },
  data: () => ({
    tabTitles: [],
    tabList: [],
    itemList: [],
    food: {
      title: '',
      attributes: []
    },
    tabPageHeight: 1334,
    wrapBgColor: '#FBFBFB',
    tabStyles: {
      bgColor: '#FFFFFF',
      titleColor: '#666666',
      activeTitleColor: '#FFFFFF',
      activeBgColor: '#F45551',
      iconWidth: 70,
      iconHeight: 70,
      width: 160,
      height: 160,
      fontSize: 25,
    },
    chooseAttributesButtonStyle: {
      width: '140px',
      height: '50px',
      lineHeight: '50px',
      backgroundColor: '#f45551',
      borderRadius: '36px'
    },
    attributesVisiabled: false,
    shoppingCartData: localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {},
    categoryIndex: 0,
    foodIndex: 0,
    language: {
      chooseAttribute: i18n.t('navigator.chooseAttribute'),
      volume:i18n.t('navigator.volume'),
    },
    outsideHeight: 0,
    tabMarginHeight: 40
  }),
  watch: {
    categories (newCategories, oldCategories) {
      /* 菜式 */
      newCategories.forEach((category, categoryIndex) => {
        this.tabTitles[categoryIndex] = {
          title: category.cat_name,
          icon: category.thumb,
          activeIcon: category.thumb_active,
          items: []
        }

        /* 菜品 */
        category.foods.forEach((food, foodIndex) => {
          this.tabTitles[categoryIndex].items[foodIndex] = {
            food_id: food.food_id,
            avatar: food.thumb,
            title: food.food_name,
            sales: food.sold_amount,
            price: {
              symbol: 'mop',
              amount: food.price
            },
            attributes: [],
            inShoppingCart: false,
            num: 0
          }

          let localStorageShoppingCart = localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {}

          if (localStorageShoppingCart && localStorageShoppingCart[food.food_id]) {
            this.tabTitles[categoryIndex].items[foodIndex].inShoppingCart = true
            this.tabTitles[categoryIndex].items[foodIndex].num = localStorageShoppingCart[food.food_id].number
          }

          /* 属性 */
          food.attrs.forEach((attribute, attributeIndex) => {
            this.tabTitles[categoryIndex].items[foodIndex].attributes[attributeIndex] = {
              attribute_id: attribute.attr_id,
              title: attribute.name,
              onOverLimit: attribute.models.length,
              isSingle: Number(attribute.is_multiple),
              models: []
            }

            /* 规格 */
            attribute.models.forEach((model, modelIndex) => {
              this.tabTitles[categoryIndex].items[foodIndex].attributes[attributeIndex].models[modelIndex] = {
                model_id: model.food_model_id,
                title: model.model_name,
                price: model.price
              }
            })
          })
        })
      })
      //这里是我首页所有渲染的数据

      //这里是计算高度
      let outsideHeight = this.$parent.getOutsideHeight()
      this.tabPageHeight = Utils.env.getPageHeight() - (outsideHeight * 2) - 30


      this.$nextTick(function(){
        this.tabList = this.tabTitles
        if(window.name == ""){
          let order_id = localStorage.getItem('order_id') ? true : false;
          if(order_id) this.$router.push('/mine-order');
          window.name = "isReload";  // 在首次进入页面时我们可以给window.name设置一个固定值 
        }else if(window.name == "isReload"){
          console.log("页面被刷新");
        }
      });


      let dataCrat = localStorage.getItem('shoppingCart') ? localStorage.getItem('shoppingCart') : false;
      if(!dataCrat) return;
      let data = JSON.parse(dataCrat);
      for(let i in data){
        let food_id = i;
        for(let ii in this.tabTitles){
          for(let iii in this.tabTitles[ii].items){
            if(this.tabTitles[ii].items[iii].food_id == food_id){
                data[i].title = this.tabTitles[ii].items[iii].title
            }
          }
        }
        //此处循环缓存好的数据
        for(let dosing in data[i].attributes){
          let likeArr = dosing.split('-');
          let str = [];
          //此处循环查询出来的数据
            for(let is in this.tabTitles){
              for(let iis in this.tabTitles[is].items){
                for(let iiis in this.tabTitles[is].items[iis].attributes){
                  //console.log(this.tabTitles[is].items[iis].attributes[iiis].models);
                  for(let iiiis in this.tabTitles[is].items[iis].attributes[iiis].models){
                    for(let likeI in likeArr){
                      if(likeArr[likeI] == this.tabTitles[is].items[iis].attributes[iiis].models[iiiis].model_id){
                         //console.log(likeArr[likeI] +"=>"+ this.tabTitles[is].items[iis].attributes[iiis].models[iiiis].model_id);
                         str.push(this.tabTitles[is].items[iis].attributes[iiis].models[iiiis].title);
                      }
                      data[i].attributes[dosing].title = str.map((item) => item).join('、')
                    }
                  }
                }
              }
           }
        }
      }
      localStorage.setItem('shoppingCart', JSON.stringify(data))
    }
  },
  mounted () {
    //console.log(data);
    //console.log(dataCrat);
  },
  methods: {
    wxcPanItemPan (e) {
      if (BindEnv.supportsEBForAndroid()) {
        this.$refs['wxc-tab-page'].bindExp(e.element)
      }
    },
    chooseAttributes (food, index, key) {
      this.attributesVisiabled = true
      this.food = food
      this.categoryIndex = index
      this.foodIndex = key
    },
    handleAttributesVisiabled (boolean) {
      this.attributesVisiabled = boolean
    },
    handleFoodNumberInShoppingCart (categoryIndex, foodIndex) {
      let shoppingCartData = localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {}
      let foodList = this.tabList[categoryIndex]
      let foodId = foodList.items[foodIndex].food_id
      foodList.items[foodIndex].num = shoppingCartData[foodId].number
      Vue.set(this.tabList, categoryIndex, foodList)

      this.handleChangeShoppingCartNumber()
    },
    wxcStepperValueChanged (event, index, key) {
      this.editShoppingCart(event.value, index, key)
    },
    /* 修改購物車 */
    editShoppingCart (num, index, key) {
      let shoppingCartData = localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {}
      let foodList = this.tabList[index]
      let foodId = foodList.items[key].food_id

      if (num < 1) {
        foodList.items[key].inShoppingCart = false
        delete shoppingCartData[foodId]
      } else {
        foodList.items[key].inShoppingCart = true
        foodList.items[key].num = num
        shoppingCartData[foodId] = {
          title: foodList.items[key].title,
          number: num,
          unitPrice: foodList.items[key].price.amount,
          symbol: foodList.items[key].price.symbol,
          avatar: foodList.items[key].avatar
        }
      }

      Vue.set(this.tabList, index, foodList)

      localStorage.setItem('shoppingCart', JSON.stringify(shoppingCartData))

      this.handleChangeShoppingCartNumber()
    },
    handleChangeShoppingCartNumber () {
      this.$emit('changeShoppingCartNumber')
    }
  }
}
</script>
